//
//  Extension+UIImage.swift
//  GZMarathon
//
//  Created by apple on 2021/11/18.
//

import Foundation

extension UIImage{
    
    func base64Str() -> String{
        var data = self.pngData()
        if data == nil {
            data = self.jpegData(compressionQuality: 1)
        }
        let base64Str = data?.base64EncodedString() ?? ""
        return base64Str
    }
    
    /// 压缩图片数据-不压尺寸
    ///
    /// - Parameters:
    ///   - maxLength: 最大长度
    /// - Returns:
    func compressImageOnlength(maxLength: Int) -> UIImage? {
        
        guard let vData = self.jpegData(compressionQuality: 1) else { return nil }
        print("压缩前kb: \( Double((vData.count)/1024))")
        if vData.count < maxLength {
            return UIImage(data: vData)
            //return vData
        }
        var compress:CGFloat = 0.9
        guard var data = self.jpegData(compressionQuality: compress) else { return nil }
        while data.count > maxLength && compress > 0.01 {
            print("压缩比: \(compress)")
            compress -= 0.02
            data = self.jpegData(compressionQuality: compress)!
        }
        print("压缩后kb: \(Double((data.count)/1024))")
        return UIImage(data: data)
        //return data
    }
    
    func compressImageMid(maxLength: Int) -> UIImage? {
        var compression: CGFloat = 1
        guard var data = self.jpegData(compressionQuality: 1) else { return nil }
        print("压缩前kb: \( Double((data.count)/1024))")
        
        if data.count < maxLength {
            return UIImage(data: data)
            //return data
        }
        print("压缩前kb", data.count / 1024, "KB")
        var max: CGFloat = 1
        var min: CGFloat = 0
        for _ in 0..<6 {
            compression = (max + min) / 2
            data = self.jpegData(compressionQuality: compression)!
            if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
                min = compression
            } else if data.count > maxLength {
                max = compression
            } else {
                break
            }
        }
        var resultImage: UIImage = UIImage(data: data)!
        return resultImage
//        if data.count < maxLength {
//            return data
//        }
//        return nil
    }
}
